package 热题100;

public class 热题48旋转二维数组 {

    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
//        int[][] ints = rotate1(arr);

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }
        System.out.println("--------------");
        rotate(arr);
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }
    }


    //开辟新的数组来旋转
    public static int[][] rotate1(int[][] arr){
        int row = arr.length;
        int[][] res = new int[row][row];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < row; j++) {
                res[j][i] = arr[i][j];
            }
        }
        arr = res;
        return arr;
    }
    public static void rotate(int[][] arr){
        int n = arr.length;
        for (int i = 0; i < n/2; i++) {
            //第一行的最后一个数字不用交换，j：0->n-1
            for (int j = i; j < n - i - 1; j++) {
                int tem = arr[i][j];
                //第一行和第一列交换，第一行i不变，j变大，arr[i][j],第一行随j变大，在进行交换
                //第一列列不变，行从n-1到0，arr[n-j-1][i]
                arr[i][j] = arr[n-j-1][i];
                arr[n-j-1][i] = arr[n-i-1][n-j-1];
                arr[n-1-i][n-1-j] = arr[j][n-i-1];
                arr[j][n-1-i] = tem;
            }
        }
    }

}
